//
//  SMNetwork.m
//  Sinmore
//
//  Created by huangtie on 2017/2/28.
//  Copyright © 2017年 Sinmore. All rights reserved.
//

#import "SMNetwork.h"
#import "SMViewController.h"

#define SMMethod_post @"POST"
#define SMMethod_get @"GET"
#define SMTimeOut 10

@implementation SMNetwork

+ (NSString *)URLParam:(NSDictionary *)dic {
    
    NSMutableString *mutableString = [[NSMutableString alloc] init];
    [dic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        if ([obj isKindOfClass:[NSString class]]) {
            NSString *strKey = key;
            NSString *strObj = obj;
            
            [mutableString appendString:strKey];
            [mutableString appendString:@"="];
            [mutableString appendString:strObj];
            [mutableString appendString:@"&"];
        }
    }];
    
    if (mutableString.length > 0) {
        if ([[mutableString substringFromIndex:(mutableString.length - 1)] isEqualToString:@"&"]) {
            [mutableString deleteCharactersInRange:NSMakeRange(mutableString.length - 1, 1)];
        }
    }
    
    return mutableString;
}

+ (NSString *)replaceUnicode:(NSString *)string {
    
    NSString *tempStr1  = [string stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
    NSString *tempStr2  = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3  = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData   *tempData  = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    [NSPropertyListSerialization propertyListWithData:tempData options:NSPropertyListImmutable format:NULL error:NULL];
    NSString *returnStr = [NSPropertyListSerialization propertyListWithData:tempData
                                                                    options:NSPropertyListImmutable
                                                                     format:NULL
                                                                      error:NULL];
    if (!returnStr) {
        return string;
    }
    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"];
}

/** 合并默认参数 **/
+ (NSDictionary *)appendCommonParam:(NSDictionary *)dict {
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:dict];
//    [params setObject:@"2" forKey:@"sm_f"]; //     来自 1:H5。 2:iOS。 3:Android
//    [params setObject:[NSBundle mainBundle].infoDictionary[@"CFBundleVersion"] forKey:@"sm_v"];
//    [params setObject:[NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"] forKey:@"sm_b"];
//    if ([[SMUserManager shareManager] isLogin]) {
//        [params setObject:[SMUserManager shareManager].token forKey:@"token"];
//    }
    return params;
}

/** 添加Cookie **/
+ (void)addCookieToManager:(AFHTTPSessionManager *)manager {
    
    NSString *OI = @"";
    NSString *OT = @"";
    if ([OI length] && [OT length]) {
        NSString *cookieValue = [NSString stringWithFormat:@"OI=%@; OT=%@", OI, OT];
        [manager.requestSerializer setValue:cookieValue forHTTPHeaderField:@"Cookie"];
    }
}

+ (NSURLSessionDataTask *)requestOnGET:(NSString *)URL
                                 param:(NSDictionary *)param
                            completion:(void (^)(NSURLSessionDataTask * _Nullable task, id _Nullable result, NSError * _Nullable error))completion
{
    return [self request:URL method:SMMethod_get param:param datas:@[] completion:completion];
}

+ (NSURLSessionDataTask *)requestOnPOST:(NSString *)URL
                                  param:(NSDictionary *)param
                             completion:(void (^)(NSURLSessionDataTask * _Nullable task, id _Nullable result, NSError * _Nullable error))completion
{
    return [self request:URL method:SMMethod_post param:param datas:@[] completion:completion];
}

+ (NSURLSessionDataTask *)requestOnUpload:(NSString *)URL
                                    param:(NSDictionary *)param
                                    datas:(NSArray <NSData *>* )datas
                               completion:(void (^)(NSURLSessionDataTask * _Nullable task, id _Nullable result, NSError * _Nullable error))completion
{
    return [self request:URL method:SMMethod_post param:param datas:datas completion:completion];
}

+ (NSURLSessionDataTask *)request:(NSString *)URL
                           method:(NSString *)method
                            param:(NSDictionary *)param
                            datas:(NSArray <NSData *> *)datas
                       completion:(void (^)(NSURLSessionDataTask * _Nullable task, id _Nullable result, NSError * _Nullable error))completion
{
    void (^successBlock)(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) = ^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        SMLog(@"\nRequest success : \n%@\n",[SMNetwork replaceUnicode:[responseObject description]]);
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            if ([[responseObject objectForKey:@"code"] integerValue] == 201) {
                [SMUserManager shareManager].token = @"";
                [[SMUserManager shareManager] login:nil callBack:nil cancelBlock:nil];
            }
        }
        
        if (completion) {
            completion(task , responseObject , nil);
        }
    };
    
    void (^failureBlock)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) = ^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        SMLog(@"\nRequest failure : \n%@\n",error);
        if (completion) {
            completion(task , nil , error);
        }
    };
    
    void (^constructingBodyBlock)(id<AFMultipartFormData>  _Nonnull formData) = ^(id<AFMultipartFormData>  _Nonnull formData) {
        for (NSData *data in datas) {
            [formData appendPartWithFileData:data name:@"image" fileName:@".png" mimeType:@"image/jpeg"];
        }
    };
    
    if (!method) {
        method = SMMethod_post;
    }
    
    if (!param) {
        param = @{};
    }
    
    param = [self appendCommonParam:param];
    SMLog(@"\nRequest URL  : %@?%@",URL,[self URLParam:param]);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [self addCookieToManager:manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];
    manager.requestSerializer.timeoutInterval = SMTimeOut;
    
    if ([method isEqualToString:SMMethod_post]) {
        return [manager POST:URL parameters:param constructingBodyWithBlock:constructingBodyBlock progress:nil success:successBlock failure:failureBlock];
    }else if ([method isEqualToString:SMMethod_get]){
        return [manager GET:URL parameters:param progress:nil success:successBlock failure:failureBlock];
    }
    return nil;
}

@end
